package classloader;

import java.io.*;

/**
 * @author ChangLiang
 * @date 2020/4/12
 */
public class MyClassLoader extends ClassLoader {

    @Override
    protected Class<?> findClass(String className) throws ClassNotFoundException {
        byte[] byteCodes = loadByteCode(className);
        if (byteCodes == null) {
            throw new ClassNotFoundException();
        } else {
            // 只要传递给该方法一个合法的字节数组 就可以转化为一个Class对象
            // 这意味着可以从任何可能的地方装载类
            return defineClass(className, byteCodes, 0, byteCodes.length);
        }
    }

    /**
     * 读取.class文件
     * @param className
     * @return .class文件的二进制字节数组
     */
    private byte[] loadByteCode(String className) {
        String fileName = "C:\\temp" + File.separatorChar + className.replace('.', File.separatorChar) + ".class";
        try (InputStream is = new FileInputStream(fileName)) {
            ByteArrayOutputStream baos = new ByteArrayOutputStream();
            byte[] buffer = new byte[1024];
            int length;
            while ((length = is.read()) != -1) {
                baos.write(buffer,0,length);
            }
            return baos.toByteArray();
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return null;
    }
}
